package com.tensquare.article.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.service.ArticleService;
import com.tensquare.entity.PageResult;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
@CrossOrigin //解决跨域问题
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    //统一异常类测试
    @RequestMapping(value = "/exception",method = RequestMethod.GET)
    public void errorTest() {
        int i = 1/0;
        System.out.println(i);
    }

    //查询文章全部数据
    @GetMapping
    public Result findAll() {
        List<Article> articleList = articleService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",articleList);
    }

    // article/{articleId} 根据ID查询文章
    @RequestMapping(value = "{articleId}", method = RequestMethod.GET)
    public Result findById(@PathVariable("articleId") String articleId) {
        Article article = articleService.findById(articleId);
        return new Result(true, StatusCode.OK,"查询成功",article);
    }

    //article 增加文章
    @PostMapping
    public Result save(@RequestBody Article article) {
        articleService.save(article);
        return new Result(true, StatusCode.OK,"新增成功");
    }


    // article/{articleId} 修改文章
    @PutMapping("{articleId}")
    public Result updateById(@PathVariable("articleId") String articleId,
                             @RequestBody Article article){
        articleService.updateById(articleId,article);
        return new Result(true, StatusCode.OK,"修改成功");
    }

    // article/{articleId} 根据ID删除文章
    @DeleteMapping("{articleId}")
    public Result deleteById(@PathVariable("articleId") String articleId) {
        articleService.deleteById(articleId);
        return new Result(true, StatusCode.OK,"删除成功");
    }

    //article/search/{page}/{size} 文章分页
    /*
        之前接收文章数据，使用pojo，但是现在是根据条件查询；
        而所有的条件都需要判断是否有值，遍历pojo的所有属性需要使用反射的方式，成本较高，性能较低；
        直接使用集合的方式遍历，会提高性能，因此这里使用Map集合来接收数据。
     */
    @GetMapping("/search/{page}/{size}")
    public Result search(@PathVariable("page") Integer page,
                         @PathVariable("size") Integer size,
                         @RequestBody Map<String, Object> map) {
        //得到Page对象
        Page<Article> pageData = articleService.search(page,size,map);
        //封装分页查询数据
        PageResult<Article> pageResult = new PageResult<>(pageData.getTotal(),pageData.getRecords());
        return new Result(true, StatusCode.OK,"查询成功",pageResult);
    }
}
